package com.lxw.multidb.modules.file.constants;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;

import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * 文件扩展名与 MIME 类型映射工具类
 * 遵循阿里代码规范，避免魔法值
 */
public class FileContentType {

    private static final Logger logger = LoggerFactory.getLogger(FileContentType.class);

    private static final String DEFAULT_MIME_TYPE = "application/octet-stream";

    // 所有支持的扩展名到 MIME 类型的映射
    private static final Map<String, String> MIME_TYPE_MAP;

    static {
        Map<String, String> map = new HashMap<>();

        // ========== 图像 ==========
        map.put("jpg", "image/jpeg");
        map.put("jpeg", "image/jpeg");
        map.put("png", "image/png");
        map.put("gif", "image/gif");
        map.put("bmp", "image/bmp");
        map.put("svg", "image/svg+xml");
        map.put("ico", "image/x-icon");
        map.put("tif", "image/tiff");
        map.put("tiff", "image/tiff");
        map.put("webp", "image/webp");

        // ========== 文档 ==========
        map.put("txt", "text/plain");
        map.put("text", "text/plain");
        map.put("log", "text/plain");

        map.put("pdf", "application/pdf");

        map.put("doc", "application/msword");
        map.put("dot", "application/msword");
        map.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        map.put("dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template");

        map.put("xls", "application/vnd.ms-excel");
        map.put("xlt", "application/vnd.ms-excel");
        map.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        map.put("xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template");

        map.put("ppt", "application/vnd.ms-powerpoint");
        map.put("pot", "application/vnd.ms-powerpoint");
        map.put("pps", "application/vnd.ms-powerpoint");
        map.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
        map.put("potx", "application/vnd.openxmlformats-officedocument.presentationml.template");
        map.put("ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow");

        // ========== Web ==========
        map.put("html", "text/html");
        map.put("htm", "text/html");
        map.put("xml", "application/xml");
        map.put("xsl", "application/xml");
        map.put("xsd", "application/xml");
        map.put("json", "application/json");
        map.put("js", "application/javascript");
        map.put("css", "text/css");

        // ========== 音频 ==========
        map.put("mp3", "audio/mpeg");
        map.put("wav", "audio/wav");
        map.put("ogg", "audio/ogg");
        map.put("aac", "audio/aac");
        map.put("flac", "audio/flac");
        map.put("m4a", "audio/mp4");

        // ========== 视频 ==========
        map.put("mp4", "video/mp4");
        map.put("avi", "video/x-msvideo");
        map.put("mov", "video/quicktime");
        map.put("wmv", "video/x-ms-wmv");
        map.put("flv", "video/x-flv");
        map.put("mkv", "video/x-matroska");
        map.put("webm", "video/webm");

        // ========== 压缩包 ==========
        map.put("zip", "application/zip");
        map.put("rar", "application/vnd.rar");
        map.put("7z", "application/x-7z-compressed");
        map.put("tar", "application/x-tar");
        map.put("gz", "application/gzip");
        map.put("tgz", "application/gzip");

        // ========== 可执行文件 / 安装包 ==========
        map.put("exe", "application/vnd.microsoft.portable-executable");
        map.put("msi", "application/x-msi");
        map.put("dmg", "application/x-apple-diskimage");

        // ========== 字体 ==========
        map.put("ttf", "font/ttf");
        map.put("otf", "font/otf");
        map.put("woff", "font/woff");
        map.put("woff2", "font/woff2");

        // ========== 代码 / 配置 ==========
        map.put("java", "text/x-java-source");
        map.put("py", "text/x-python");
        map.put("sh", "application/x-shellscript");
        map.put("yaml", "application/yaml");
        map.put("yml", "application/yaml");
        map.put("properties", "text/plain");
        map.put("ini", "text/plain");

        // ========== 其他 ==========
        map.put("csv", "text/csv");
        map.put("rtf", "application/rtf");

        MIME_TYPE_MAP = Collections.unmodifiableMap(map);
    }

    /**
     * 根据文件名获取 MediaType
     *
     * @param fileName 文件名（如 "report.pdf"）
     * @return 对应的 MediaType，若无法识别则返回 application/octet-stream
     */
    public static MediaType getContentType(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return MediaType.APPLICATION_OCTET_STREAM;
        }

        try {
            int lastDotIndex = fileName.lastIndexOf('.');
            if (lastDotIndex <= 0 || lastDotIndex == fileName.length() - 1) {
                return MediaType.APPLICATION_OCTET_STREAM;
            }

            String extension = fileName.substring(lastDotIndex + 1).toLowerCase(Locale.ROOT);
            String mimeType = MIME_TYPE_MAP.getOrDefault(extension, DEFAULT_MIME_TYPE);
            return MediaType.parseMediaType(mimeType);
        } catch (Exception e) {
            logger.warn("解析文件 {} 的 ContentType 失败，使用默认类型", fileName, e);
            return MediaType.APPLICATION_OCTET_STREAM;
        }
    }

    /**
     * 获取默认 MIME 类型（application/octet-stream）
     */
    public static MediaType getDefaultMediaType() {
        return MediaType.APPLICATION_OCTET_STREAM;
    }
}